package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.service.db.UserInfoService;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * java
 */
@Service
public class TestSoulManager {


    @Reference
    private TestSoulService testSoulService;

    @Reference
    private UserInfoService userInfoService;


    //查询测灵魂问卷列表
    public List<TestSoulVo> findSoulQuestionList() {

        //查询用户问卷解锁状态
        UserIsStatus userIsStatus = testSoulService.findStatusByUserId(UserHolder.get().getId());
        if (userIsStatus == null) { //用户没有测试状态
            userIsStatus = new UserIsStatus()
                    .setUserId(UserHolder.get().getId().intValue()) //用户id
                    .setLowScore(null) //设置初级问卷分数为空
                    .setMiddleLevelLock("1") //设置中级问卷为锁住状态
                    .setHighLevelLock("1"); //设置高级问卷为锁住状态

            //初始化用户问卷解锁状态
            testSoulService.saveStatus(userIsStatus);
        }

        //查询所有试卷类型
        List<Questionnaire> questionnaireList = testSoulService.findQuestionnaire();

        //创建返回对象
        List<TestSoulVo> testSoulVoList = new ArrayList<>();

        //遍历类型--进行封装
        if (CollectionUtil.isNotEmpty(questionnaireList)) {
            for (Questionnaire questionnaire : questionnaireList) {

                //创建返回Vo对象
                TestSoulVo testSoulVo = new TestSoulVo();

                testSoulVo.setId(questionnaire.getQuestionnaireId());  //问卷编号
                testSoulVo.setName(questionnaire.getName()); //问卷名称
                testSoulVo.setCover(questionnaire.getCover());  //封面
                testSoulVo.setLevel(questionnaire.getLevel());  //级别
                testSoulVo.setStar(questionnaire.getStar()); //星别（例如：2颗星，3颗星，5颗星）

                if (StrUtil.equals(questionnaire.getQuestionnaireId(), "1")) {  //初级默认解锁状态
                    testSoulVo.setIsLock(0); //是否锁住（0解锁，1锁住）
                    testSoulVo.setReportId(userIsStatus.getLowReportId() != null ? userIsStatus.getLowReportId() : null); //最新报告id
                } else {
                    if (StrUtil.equals(questionnaire.getQuestionnaireId(), "2")) {
                        testSoulVo.setIsLock(Integer.parseInt(userIsStatus.getMiddleLevelLock())); //是否锁住（0解锁，1锁住）
                        testSoulVo.setReportId(userIsStatus.getMiddleReportId() != null ? userIsStatus.getMiddleReportId() : null); //最新报告id
                    }
                    if (StrUtil.equals(questionnaire.getQuestionnaireId(), "3")) {
                        testSoulVo.setIsLock(Integer.parseInt(userIsStatus.getHighLevelLock())); //是否锁住（0解锁，1锁住）
                        testSoulVo.setReportId(userIsStatus.getHighReportId() != null ? userIsStatus.getHighReportId() : null); //最新报告id
                    }
                }

                //查询问卷列表
                List<Questions> questionsList = testSoulService.findQuestionsList();

                //将questions对象封装成questionsVo
                List<QuestionsVo> questionsVoList = new ArrayList<>();

                for (Questions questions : questionsList) {
                    if (!questionnaire.getQuestionnaireId().equals(questions.getPaperId())) {  //如果不是这个级别的问题,结束本次循环
                        continue;
                    }
                    QuestionsVo questionsVo = new QuestionsVo();
                    questionsVo.setId(questions.getId() + ""); //问题id
                    questionsVo.setQuestion(questions.getQuestion()); //问题内容
                    //查询问题的选项
                    List<Answer> answerList = testSoulService.findQuestionsAnswer(questions.getId());
                    //将answer对象封装成answerVo对象
                    ArrayList<AnswersVo> answersVos = new ArrayList<>();
                    for (Answer answer : answerList) {
                        AnswersVo answersVo = new AnswersVo();
                        answersVo.setId(answer.getId());  //选项编号
                        answersVo.setOption(answer.getContent()); //选项内容
                        answersVos.add(answersVo);
                    }
                    questionsVo.setOptions(answersVos);
                    questionsVoList.add(questionsVo);
                }
                testSoulVo.setQuestions(questionsVoList);


                testSoulVoList.add(testSoulVo);
            }
        }

        return testSoulVoList;
    }


    //测灵魂问卷提交
    public String saveSoulQuestion(Map<String, List<Answers>> map) {

        //接收问卷试题及选项参数
        List<Answers> answersList = map.get("answers");

        //初始化分数
        Integer score = 0;


        for (Answers answers : answersList) {

            //查询选项对应的分数
            Answer answer = testSoulService.findOptionScore(answers.getOptionId());

            if (answer != null) {

                //计算分数
                score += Integer.parseInt(answer.getScore());
            }
        }

       /* Integer type = 1;

        if (score >= 0 && score <= 20) {
            type = 1;
        } else if (score >= 21 && score <= 40) {
            type = 2;
        } else if (score >= 41 && score <= 55) {
            type = 3;
        } else if (score >= 56 && score <= 100) {
            type = 4;
        }*/

        //查询分数对应的类型
        Integer testResult = testSoulService.findTestResult(score);

        //获取问题id,查询问题级别
        Answers answers = answersList.get(1); //随便获取一道试题
        String questionId = answers.getQuestionId(); //根据试题获得试题编号

        //根据编号查询试题属于哪个级别的试卷
        Questions questions = testSoulService.findPaperIdByQuestionId(questionId);

        //查询该用户的问卷结果表
        UserIsStatus userIsStatus = testSoulService.findStatusByUserId(UserHolder.get().getId());

        //对各个级别的问卷做相应操作
        switch (questions.getPaperId()) {
            case "1":
                userIsStatus.setMiddleLevelLock("0"); //解锁中级问卷
                userIsStatus.setLowScore(score + ""); //设置初级问卷分数
                userIsStatus.setLowReportId(testResult + ""); //设置初级问卷报告id
                break;
            case "2":
                userIsStatus.setHighLevelLock("0"); //解锁高级问卷
                userIsStatus.setMiddleScore(score + ""); //设置中级问卷分数
                userIsStatus.setMiddleReportId(testResult + ""); //设置中级问卷报告id
                break;
            case "3":
                userIsStatus.setHighScore(score + ""); //设置高级问卷分数
                userIsStatus.setHighReportId(testResult + ""); //设置高级问卷报告id
                break;
        }

        //更新用户结果表
        testSoulService.updateStatus(userIsStatus);

        //返回报告id
        return testResult + "";
    }

    //测灵魂查询结果
    public ReportVo findResult(Integer id) {

        //根据id查询对应的类型
        TestResult testResult = testSoulService.findResult(id);

        //封装结果vo
        ReportVo reportVo = new ReportVo();
        reportVo.setConclusion(testResult.getContent()); //设置测试结果
        reportVo.setCover(testResult.getCover()); //设置结果封面

        //查询维度
        List<UserNature> userNatureList = testSoulService.findUserNature(UserHolder.get().getId());

        List<DimensionsVo> dimensionsVoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(userNatureList)) {
            for (UserNature userNature : userNatureList) {

                //封装维度vo
                DimensionsVo dimensionsVo = new DimensionsVo();
                dimensionsVo.setKey(userNature.getKey());
                dimensionsVo.setValue(userNature.getValue());

                dimensionsVoList.add(dimensionsVo);
            }

        }

        reportVo.setDimensions(dimensionsVoList); //设置维度

        //查询相似的人
        List<UserIsStatus> userIsStatusList = testSoulService.findScore(UserHolder.get().getId());

        List<SimilarYouVo> similarYouVoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(userIsStatusList)) {

            for (UserIsStatus userIsStatus : userIsStatusList) {

                Integer userId = userIsStatus.getUserId();

                UserInfo userInfo = userInfoService.findByUserId(userId.longValue());

                //封装
                SimilarYouVo similarYouVo = new SimilarYouVo();
                similarYouVo.setAvatar(userInfo.getAvatar());
                similarYouVo.setId(userInfo.getId().intValue());

                similarYouVoList.add(similarYouVo);
            }
        }

        reportVo.setSimilarYou(similarYouVoList); //设置相似的人

        return reportVo;
    }
}
